package com.ittsang.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.ittsang.dto.ArticleTypeDTO;
import com.ittsang.dto.PageDTO;
import com.ittsang.dto.R;
import com.ittsang.dto.UserDTO;
import com.ittsang.mapper.ArticleTypeMapper;
import com.ittsang.pojo.ArticleType;
import com.ittsang.pojo.Race;
import com.ittsang.service.ArticleTypeService;
import com.ittsang.utils.UserHolder;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

@Slf4j
@Service
public class ArticleTypeServiceImpl implements ArticleTypeService {

    @Autowired
    private ArticleTypeMapper articleTypeMapper;

    @Override
    public R getArticleTypeList() {
        List<ArticleType> articleType = articleTypeMapper.getArticleTypeList();
        return R.ok("查询成功").put("getArticleTypeList", articleType);
    }

    @Override
    public R insertArticleType(ArticleTypeDTO articleTypeDTO) {
        int num = articleTypeMapper.insertArticleType(articleTypeDTO);
        return num > 0?R.ok("添加成功"):R.error("添加失败");
    }

    @Override
    public R deletedArticleTypeById(Integer articleTypeId) {
        int num = articleTypeMapper.deletedArticleTypeById(articleTypeId);
        return num > 0?R.ok("删除成功"):R.error("删除失败");
    }

    @Override
    public R alterArticleTypeById(ArticleTypeDTO articleTypeDTO) {
        int num = articleTypeMapper.alterArticleTypeById(articleTypeDTO);
        return num > 0?R.ok("修改成功"):R.error("修改失败");
    }

    @Override
    public R getArticleType(PageDTO pageDTO) {
        UserDTO user = UserHolder.getUser();
        if (user.getRoleId().equals(0)) {
            return R.error("用户无权限");
        }
        List<ArticleType> articleType = articleTypeMapper.getArticleTypeList();
        int pageNum = pageDTO.getPageNum();
        int pageSize = pageDTO.getPagesize();
        PageHelper.startPage(pageNum,pageSize);
        int skip= (pageNum-1)*pageSize;
        Page<ArticleType> page = new Page<>(pageNum, pageSize);
        page.setTotal(articleType.size());
        List<ArticleType> articleDTOList = articleType.stream().skip(skip)
                .limit(pageSize).collect(Collectors.toList());
        page.addAll(articleDTOList);
        return R.ok("查询成功").put("articleTypeList", page).put("total", page.getTotal());
    }

    @Override
    public R getArticleTypeById(Integer articleTypeId) {
        ArticleType articleType = articleTypeMapper.getArticleTypeById(articleTypeId);
        return R.ok("获取成功").put("articleType", articleType);
    }
}
